package cn.madis.filter;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


@Component
public class LoginCheckFilter extends ZuulFilter {
    //filter类型  pre前置
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }
    //执行顺序
    @Override
    public int filterOrder() {
        return 0;
    }

    /*返回结果决定 是否要执行run方法*/
    @Override
    public boolean shouldFilter() {
        //1. 获取request中url
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        String uri = request.getRequestURI();
        //2. 判断是否含有 static  login register公共资源有放行
        if (uri.endsWith("login") || uri.endsWith("register") || uri.contains("static")){
            //不做登录检查反回false
            return false;
        }

        //3. 返回true做登录检查
        return false;
    }

    //核心业务方法
    @Override
    public Object run() throws ZuulException {
        //1.获取请求对象
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        //响应对象
        HttpServletResponse response = RequestContext.getCurrentContext().getResponse();
        //2.获取请求头中的 token
        String token = request.getHeader("token");
        //3.如果没有token，登录检查失败 ，
        if (StringUtils.isBlank(token)){
            //3.1.返回登录检查失败的错误信息 :{ success:false, message:"登录检查失败，请重新登录"}
            Map<String,Object> resultMap = new HashMap<>();
            resultMap.put("success",false);
            resultMap.put("message","登录检查失败，请重新登录");
            resultMap.put("data",null);
            //中文编码
            response.setContentType("application/json;charset=utf-8");
            //把map转成json字符串，写到浏览器
            String s = JSON.toJSONString(resultMap);
            // 设置状态码
            response.setStatus(403);
            try {
                response.getWriter().write(s);
            } catch (IOException e) {
                e.printStackTrace();
            }
            //3.2.阻止filter继续往后执行
            RequestContext.getCurrentContext().setSendZuulResponse(false);
        }
        return null;
    }
}
